package com.feinno.bug.actcache.service.impl;

import com.feinno.bug.actcache.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by chenxuwu on 2018/3/20.
 */
@Service("redisService")
public class RedisServiceImpl implements RedisService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void del(String key) {
        redisTemplate.opsForList().trim(key, 1, 0);
    }


    @Override
    public Long leftPushAll(String key, Collection<String> values) {
        return redisTemplate.opsForList().leftPushAll(key, values);
    }

    @Override
    public <T> T range(String key, long start, long end) {
        ListOperations<String, String> oper = redisTemplate.opsForList();
        return (T) oper.range(key, start, end);
    }

    @Override
    public void setStringToRedis(List<String> list, String key) {
        SessionCallback<Object> sessionCallback = new SessionCallback<Object>() {
            @Override
            public <K, V> Object execute(RedisOperations<K, V> redisOperations) throws DataAccessException {
                for (String item : list) {
                    ListOperations<String, String> oper = redisTemplate.opsForList();
                    oper.leftPush(key, item);
                }
                return null;
            }
        };
        //System.out.println("批量生成" + userMSGS.size() + "耗时：" + (System.currentTimeMillis() - time));
        redisTemplate.executePipelined(sessionCallback);
    }

}
